package com.education.ai.controller;

import com.education.ai.entity.MediaResource;
import com.education.ai.service.MediaResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 多媒体资源控制器
 */
@RestController
@RequestMapping("/api/media-resources")
@Slf4j
public class MediaResourceController {

    @Autowired
    private MediaResourceService mediaResourceService;

    /**
     * 获取所有多媒体资源
     */
    @GetMapping
    public List<MediaResource> getAllMediaResources() {
        return mediaResourceService.getAllMediaResources();
    }

    /**
     * 根据ID获取多媒体资源
     */
    @GetMapping("/{id}")
    public ResponseEntity<MediaResource> getMediaResourceById(@PathVariable Long id) {
        MediaResource mediaResource = mediaResourceService.getMediaResourceById(id);
        if (mediaResource != null) {
            return ResponseEntity.ok(mediaResource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建多媒体资源
     */
    @PostMapping
    public MediaResource createMediaResource(@RequestBody MediaResource mediaResource) {
        return mediaResourceService.saveMediaResource(mediaResource);
    }

    /**
     * 更新多媒体资源
     */
    @PutMapping("/{id}")
    public ResponseEntity<MediaResource> updateMediaResource(@PathVariable Long id, @RequestBody MediaResource mediaResource) {
        MediaResource existingResource = mediaResourceService.getMediaResourceById(id);
        if (existingResource == null) {
            return ResponseEntity.notFound().build();
        }
        
        mediaResource.setId(id);
        MediaResource updatedResource = mediaResourceService.saveMediaResource(mediaResource);
        return ResponseEntity.ok(updatedResource);
    }

    /**
     * 删除多媒体资源
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteMediaResource(@PathVariable Long id) {
        MediaResource existingResource = mediaResourceService.getMediaResourceById(id);
        if (existingResource == null) {
            return ResponseEntity.notFound().build();
        }
        
        mediaResourceService.deleteMediaResource(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 根据资源类型获取多媒体资源
     */
    @GetMapping("/type/{resourceType}")
    public List<MediaResource> getMediaResourcesByType(@PathVariable String resourceType) {
        return mediaResourceService.getMediaResourcesByType(resourceType);
    }

    /**
     * 根据学科获取多媒体资源
     */
    @GetMapping("/subject/{subject}")
    public List<MediaResource> getMediaResourcesBySubject(@PathVariable String subject) {
        return mediaResourceService.getMediaResourcesBySubject(subject);
    }

    /**
     * 根据年级获取多媒体资源
     */
    @GetMapping("/grade/{grade}")
    public List<MediaResource> getMediaResourcesByGrade(@PathVariable String grade) {
        return mediaResourceService.getMediaResourcesByGrade(grade);
    }

    /**
     * 生成教学图片
     */
    @PostMapping("/generate")
    public ResponseEntity<?> generateImages(@RequestBody Map<String, Object> requestBody) {
        try {
            log.info("收到生成图片请求: {}", requestBody);

            // 请求参数验证
            if (requestBody == null) {
                log.warn("请求体为空");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "请求参数错误");
                errorResponse.put("message", "请求体不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 必要参数验证
            if (requestBody.get("subject") == null ||
                requestBody.get("grade") == null ||
                requestBody.get("topic") == null) {

                log.warn("缺少必要参数");
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "请求参数错误");
                errorResponse.put("message", "缺少必要参数: subject、grade、topic");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 获取教师ID - 首先尝试从请求体获取
            String teacherId = (String) requestBody.get("teacher_id");
            
            // 如果请求体中没有教师ID，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = com.education.ai.util.TeacherContext.getTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }
            
            // 尝试处理imageCount
            Integer imageCount = 1;
            if (requestBody.get("imageCount") != null) {
                try {
                    imageCount = Integer.parseInt(requestBody.get("imageCount").toString());
                    if (imageCount <= 0) {
                        imageCount = 1;
                    }
                } catch (NumberFormatException e) {
                    log.warn("imageCount格式错误: {}", requestBody.get("imageCount"));
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("error", "请求参数错误");
                    errorResponse.put("message", "imageCount必须是正整数");
                    return ResponseEntity.badRequest().body(errorResponse);
                }
            }

            // 检查size格式
            String size = (String) requestBody.get("size");
            if (size != null && !size.contains("*")) {
                log.warn("size格式错误: {}", size);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "请求参数错误");
                errorResponse.put("message", "size参数格式错误，正确格式示例: 1024*1024");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 调用服务生成图片，并传递teacher_id
            MediaResource result = mediaResourceService.generateImageWithWanxiang(
                (String) requestBody.get("subject"),
                (String) requestBody.get("grade"),
                (String) requestBody.get("topic"),
                (String) requestBody.get("description"),
                imageCount,
                size,
                teacherId
            );

            log.info("图片生成成功，返回资源ID: {}", result.getId());
            // 包装响应为前端期望的格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", result);
            response.put("success", true);
            response.put("message", "图片生成成功");
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            log.warn("参数验证失败: {}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("error", "参数错误");
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            log.error("生成图片失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("error", "生成图片失败");
            response.put("message", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 生成教学视频
     */
    @PostMapping("/generate-video")
    public ResponseEntity<MediaResource> generateVideo(@RequestBody Map<String, Object> requestBody) {
        try {
            String subject = (String) requestBody.get("subject");
            String grade = (String) requestBody.get("grade");
            String topic = (String) requestBody.get("topic");
            String description = (String) requestBody.get("description");
            Integer duration = Integer.valueOf(requestBody.get("duration").toString());

            if (subject == null || grade == null || topic == null || description == null || duration == null) {
                return ResponseEntity.badRequest().build();
            }

            // 获取教师ID - 首先尝试从请求体获取
            String teacherId = (String) requestBody.get("teacher_id");
            
            // 如果请求体中没有教师ID，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = com.education.ai.util.TeacherContext.getTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }

            // 调用带teacherId参数的视频生成服务
            MediaResource generatedVideo = mediaResourceService.generateVideo(
                subject, grade, topic, description, duration, teacherId);
            
            return ResponseEntity.ok(generatedVideo);
        } catch (Exception e) {
            log.error("生成教学视频失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 获取图片聊天历史
     */
    @GetMapping("/image/chat/history")
    public ResponseEntity<?> getImageChatHistory() {
        try {
            log.info("获取图片聊天历史");
            // 返回空列表，实际项目中应从数据库查询
            Map<String, Object> response = new HashMap<>();
            response.put("data", new ArrayList<>());
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取图片聊天历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "获取聊天历史失败");
            response.put("message", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 清空图片聊天历史
     */
    @DeleteMapping("/image/chat/history")
    public ResponseEntity<?> clearImageChatHistory() {
        try {
            log.info("清空图片聊天历史");
            // 实际项目中应从数据库删除历史记录
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "聊天历史已清空");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("清空图片聊天历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "清空聊天历史失败");
            response.put("message", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 图片AI聊天接口
     */
    @PostMapping("/image/chat")
    public ResponseEntity<?> chatWithImageAI(@RequestBody Map<String, Object> requestBody) {
        try {
            log.info("收到图片AI聊天请求: {}", requestBody);
            // 模拟AI回复
            Map<String, Object> response = new HashMap<>();
            Map<String, Object> data = new HashMap<>();
            
            data.put("messageId", UUID.randomUUID().toString());
            data.put("content", "您好，我是图片生成助手。我可以根据您的描述生成教学图片。请问有什么我可以帮助您的？");
            data.put("timestamp", System.currentTimeMillis());
            
            response.put("data", data);
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("图片AI聊天失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "聊天失败");
            response.put("message", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取图片资源列表
     */
    @GetMapping("/list")
    public ResponseEntity<?> getMediaResourcesList() {
        try {
            log.info("获取图片资源列表");
            List<MediaResource> resources = mediaResourceService.getAllMediaResources();
            
            Map<String, Object> response = new HashMap<>();
            response.put("data", resources);
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取图片资源列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "获取资源列表失败");
            response.put("message", e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取媒体资源历史记录
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getMediaResourceHistory(
            @RequestParam(required = false) String teacherId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size) {
        try {
            // 如果未提供teacherId，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                // 这里应该有获取当前用户ID的逻辑，暂时用空字符串代替
                teacherId = ""; // 实际项目中应该从会话或上下文中获取
            }

            if (teacherId == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "未提供教师ID且无法从上下文获取");
                errorResponse.put("data", null);
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 从数据库查询分页数据
            Page<MediaResource> resourcePage = mediaResourceService.getMediaResourcesByTeacherId(teacherId, PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createdTime")));
            
            // 转换为前端所需的格式
            List<Map<String, Object>> resourceList = resourcePage.getContent().stream()
                    .map(resource -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", resource.getId());
                        map.put("subject", resource.getSubject());
                        map.put("grade", resource.getGrade());
                        map.put("topic", resource.getTopic());
                        map.put("resourceType", resource.getResourceType());
                        map.put("title", resource.getTitle());
                        map.put("description", resource.getDescription());
                        map.put("url", resource.getUrl());
                        map.put("format", resource.getFormat());
                        map.put("duration", resource.getDuration());
                        map.put("createdTime", resource.getCreatedTime());
                        return map;
                    })
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", resourceList);
            response.put("total", resourcePage.getTotalElements());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取媒体资源历史记录失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
} 